package handler

import (
	"chat/api/request"
	"chat/consts"
	"chat/internal/dao"
	"chat/internal/model"
	"chat/pkg"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"time"
)

func Ping(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

func Register(c *gin.Context) {
	var req request.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "该用户已存在，禁止注册",
			"data":    nil,
		})
		return
	}
	result := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
		UType:    req.UType,
	})
	if !result {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "用户注册失败",
			"data":    false,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "用户注册成功",
		"data":    true,
	})
}

func Login(c *gin.Context) {
	var req request.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile, Password: pkg.Md5(req.Password)}, &user)
	if user.Id == 0 {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "账号或密码错误，请重新输入",
			"data":    nil,
		})
		return
	}
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 3600*24*7,
		},
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "token生成失败",
			"data":    nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "token生成成功",
		"data":    token,
	})
}

func GetUserList(c *gin.Context) {
	var req request.GetUserListReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "参数错误",
			"data":    nil,
		})
		return
	}
	pageDto := dao.PageDto{
		Page:     req.Page,
		PageSize: req.PageSize,
	}
	var userList []model.User
	paginate, _ := dao.Paginate(&model.User{

		UType: req.UType,
	}, pageDto, &userList)
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "客服列表分页展示成功",
		"data":    paginate,
	})
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "图片上传失败",
			"data":    nil,
		})
		return
	}
	dsn := "D:\\gowork\\src\\chat\\static\\upload\\" + file.Filename
	err = c.SaveUploadedFile(file, dsn)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    10000,
			"message": "图片上传失败",
			"data":    nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    http.StatusOK,
		"message": "图片上传成功",
		"data":    fmt.Sprintf("http://127.0.0.1:8080/upload/" + file.Filename),
	})
}
